package com.kzd.btgame.main.mine

import android.graphics.Rect
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.ConvertUtils
import com.kzd.btgame.app.URL_PAY_SAVING
import com.kzd.btgame.custom.setOnClickAntiShakeListener
import com.kzd.btgame.custom.setTransitionStatus
import com.kzd.btgame.databinding.FragmentMemberMoneyBinding
import com.kzd.btgame.jetpack.vm.MineViewModel
import com.kzd.btgame.main.mine.adapter.MemberMoneyCardAdapter
import com.kzd.btgame.main.popup.PaymentBottomPopup
import com.kzd.btgame.main.toMineRichTextActivityUrl
import com.module.lemlin.http.Status
import com.module.lemlin.owner.OwnerViewBindingFragment
import com.module.lemlin.owner.ownerViewModel
import java.lang.StringBuilder

class MemberMoneyFragment : OwnerViewBindingFragment<FragmentMemberMoneyBinding>() {

    companion object {
        fun newInstance(): MemberMoneyFragment {
            return MemberMoneyFragment()
        }
    }

    private val mMemberMoneyCardAdapter = MemberMoneyCardAdapter()

    private val mPaymentBottomPopup: PaymentBottomPopup by lazy {
        PaymentBottomPopup(requireContext(), onMoneySaving = { _, type, moneySaving ->
            mViewModel.mineMemberMoneyOrder(
                moneySaving.type.toString(),
                if (moneySaving.first_charge == 1)
                    moneySaving.first_money.toString()
                else
                    moneySaving.pay_money.toString(),
                type.toString()
            )
        })
    }

    private val mViewModel:MineViewModel by lazy {
        ownerViewModel(owner = this)
    }

    override val inflate: (LayoutInflater, ViewGroup?, Boolean) -> FragmentMemberMoneyBinding
        get() = FragmentMemberMoneyBinding::inflate

    override fun initView() {
        mViewBinding.rvMemberMoneyCardBody.apply {
            layoutManager = LinearLayoutManager(context).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }
            if (itemDecorationCount > 0)
                return
            addItemDecoration(ItemDecoration())
        }.adapter = mMemberMoneyCardAdapter.apply {
            setOnItemClickListener { _, _, position ->
                selectPosition = position
                val itemDate = getItem(position)
                mViewBinding.tvMemberMoneyPrice.text = StringBuilder().append("¥\t").append(
                    if (itemDate.first_charge == 1) itemDate.first_money else itemDate.pay_money
                ).toString()
            }
        }

        mViewBinding.rvMemberMoneyPayment.setOnClickAntiShakeListener {
            val memberSaving = mViewModel.memberMoneyCardLiveData.value?.data?.data?.saving
                ?: return@setOnClickAntiShakeListener
            if (memberSaving.isNullOrEmpty())
                return@setOnClickAntiShakeListener
            mPaymentBottomPopup.fillData(memberSaving[mMemberMoneyCardAdapter.selectPosition])
                .showPopupWindow()
        }
    }

    override fun initData() {
        mViewModel.mineMemberMoneyCard()
    }

    override fun initViewMode() {
        mViewModel.memberMoneyCardLiveData.observe(viewLifecycleOwner, { response ->

            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe

            val coupon = data.coupon
//            tvMemberMoneyCardTitle.text = StringBuilder()
//                .append("每天获得1张").append(coupon.name)
//            tvMemberMoneyCardBill.text = StringBuilder()
//                .append(coupon.name).append("*每天1张")
            mViewBinding.tvMemberMoneyCardTime.text = StringBuilder()
                .append(coupon.day).append("天")

            val saving = data.saving.map {
                it.apply { first_charge = data.first_charge }
            }.toMutableList()
            mMemberMoneyCardAdapter.setNewInstance(saving)

            if (saving.isNullOrEmpty()) {
                return@observe
            }
            mViewBinding.tvMemberMoneyPrice.text = StringBuilder().append("¥\t").append(
                if (data.first_charge == 1) saving[0].first_money else saving[0].pay_money
            ).toString()
        })
        mViewModel.moneyOrderLiveData.observe(viewLifecycleOwner, { response ->
            this.setTransitionStatus(response)
            if (response.status != Status.SUCCESS)
                return@observe
            val data = response.data?.data
                ?: return@observe
            val url = StringBuilder(URL_PAY_SAVING).append("&id=")
                .append(data).toString()
            toMineRichTextActivityUrl(
                title = "支付", url = url
            )
        })
    }


    inner class ItemDecoration : RecyclerView.ItemDecoration() {
        override fun getItemOffsets(
            outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State
        ) {
            val position: Int = parent.getChildAdapterPosition(view)
            if (position == 0) {
                outRect.left = ConvertUtils.dp2px(15f)
            }
            if (position == state.itemCount - 1) {
                outRect.right = ConvertUtils.dp2px(15f)
            } else {
                outRect.right = ConvertUtils.dp2px(13f)
            }
        }
    }

}